/*
*********************************
	  SF2D Engine
*********************************

	By Julian Williams
	October 20, 2010
**********************************

	Description:

		Physics engine callbacks
	defined here
***********************************
*/


#include <iostream>
using namespace std;

#include "physics_listener.h"
#include "entity.h"



void PhysicsListener::PreSolve(b2Contact *contact, const b2Manifold *oldManifold)
{
	b2WorldManifold worldManifold;

  contact->GetWorldManifold(&worldManifold);

  b2PointState state1[2], state2[2];

  b2GetPointStates(state1, state2, oldManifold, contact->GetManifold());

  if (state2[0] == b2_addState)
  {

	b2Body* bodyA = contact->GetFixtureA()->GetBody();
	b2Body* bodyB = contact->GetFixtureB()->GetBody();

	Entity *bod_1 = (Entity*) bodyA->GetUserData();
	Entity *bod_2 = (Entity*) bodyB->GetUserData();
	
	if(bod_1 != NULL)
	{
	
		if(bod_1->type == ET_PROJECTILE)
		{ 
			//cout << "is Called 1: "<< bod_1->damage << endl; 
			bod_1->MarkRemoval();
			
		}
	}
	
	if(bod_2 != NULL)
	{
		if(bod_2->type == ET_PROJECTILE) 
		{
			bod_2->MarkRemoval();//cout << "is Called 2"<< endl;
		}
	}
	
  }
	
}//EoF




void PhysicsListener::BeginContact(b2Contact *contact)
{
	b2WorldManifold worldManifold;

	contact->GetWorldManifold(&worldManifold);


	b2Body* bodyA = contact->GetFixtureA()->GetBody();
	b2Body* bodyB = contact->GetFixtureB()->GetBody();

	Entity *bod_1 = (Entity*) bodyA->GetUserData();
	Entity *bod_2 = (Entity*) bodyB->GetUserData();
	
	if(bod_1 != NULL && bod_2 != NULL)
	{
		
		bod_1->OnCollision(bod_2);	
		bod_2->OnCollision(bod_1);

		/*
		if(bod_1->type == ET_PROJECTILE)
		{ 
			//cout << "is Called 1: "<< bod_1->damage << endl; 
			bod_1->MarkRemoval();
			
		}

		if(bod_2->type == ET_PROJECTILE) 
		{
			bod_2->MarkRemoval();//cout << "is Called 2"<< endl;
		}
		*/
	}
}